package com.websuites.ejb.jndi;

import java.io.InputStream;
import java.util.Properties;

import javax.naming.InitialContext;

import com.websuites.utils.LogUtil;

public class JNDIUtil {
	
	private static InitialContext ctx;
	
	public static synchronized Object lookup(String srvClazz) {
		try {
			Properties prop = new Properties();
			if(ctx==null){
				LogUtil.info("load jndi.properties file from path: "+JNDIFactory.class.getClassLoader().getResource(".").getPath());
				InputStream is = JNDIFactory.class.getClassLoader().getResourceAsStream("jndi.properties");
				String message = "jndi configuration in "+JNDIFactory.class.getClassLoader().getResource(".").getPath()+"jndi.properties is not found!";
				if (is != null) {
					prop.load(is);
					is.close();
					message = "jndi load successful!";
					LogUtil.info(message);
					ctx = new InitialContext(prop);
				} else {
					LogUtil.error(message);
				}
			}
			if(ctx!=null){
				JNDIFinder finder = JNDIFactory.getFinder(prop.getProperty("deploy.server"));
				return finder.lookup(ctx, srvClazz);
			}
		} catch (Exception e) {
			ctx=null;
			LogUtil.info("jndi load fauilt!");
			e.printStackTrace();
		}
		return null;
	}
	
	public static synchronized Object lookupJNDI(String jndi) {
		
		try {
			Properties prop = new Properties();
			if(ctx==null){
				LogUtil.info("load jndi.properties file from path: "+JNDIFactory.class.getClassLoader().getResource(".").getPath());
				InputStream is = JNDIFactory.class.getClassLoader().getResourceAsStream("jndi.properties");
				String message = "jndi configuration in "+JNDIFactory.class.getClassLoader().getResource(".").getPath()+"jndi.properties is not found!";
				if (is != null) {
					prop.load(is);
					is.close();
					message = "jndi load successful!";
					LogUtil.info(message);
					ctx = new InitialContext(prop);
					
				} else {
					LogUtil.error(message);
				}
			}
			if(ctx!=null){
				JNDIFinder finder = JNDIFactory.getFinder(prop.getProperty("deploy.server"));
				return finder.lookupJNDI(ctx, jndi);
			}
		} catch (Exception e) {
			ctx=null;
			LogUtil.info("jndi load fauilt!");
			e.printStackTrace();
		}
		return null;
	}
	
}